<template>
  <NavBar safe-area-inset-top title="注册"
    :left-arrow="true" @click-left="gotoLogin" />
  <div class="register-page">
    <div class="register-header">
      <Image :src="Logo" fit="contain"
        width="120"></Image>
    </div>

    <Form ref="form" class="form">
      <Field v-model="params.nickName"
        class="field" name="nickName"
        placeholder="请输入昵称"
        :rules="[{ required: true, message: '请输入昵称' }]" />
      <Field v-model="params.phoneNumber"
        class="field" name="phoneNumber"
        placeholder="请输入手机号"
        :rules="phoneRules" />
      <Field v-model="params.code" name="code"
        class="field" placeholder="请输入6位验证码"
        :rules="[{ required: true, message: '请输入验证码' }]">
        <template #button>
          <Button size="mini" type="primary"
            :disabled="!showSendCode" block
            :loading="smsCodeLoading"
            @click="sendSmsCode">
            {{ countdown > 0 ? `${countdown}s后重发` : '验证码' }}
          </Button>
        </template>
      </Field>

      <Field v-model="params.password"
        name="password" :type="passwordType"
        @click-right-icon="showPassword = !showPassword"
        :right-icon="rightIcon" class="field"
        placeholder="8-16位字母数字组合"
        :rules="passwordRules"
        left-icon="lock-o" />
    </Form>
    <div class="actions-button">
      <div class="extra-actions">
        已有账号？<a @click="gotoLogin">立即登录</a>
      </div>
      <Button round block type="primary"
        @click="handleSubmit" class="register-btn"
        :loading="loading">
        立即注册
      </Button>
    </div>
  </div>
  <Verify @success="success" mode="pop"
    captchaType="clickWord"
    :imgSize="{ width: '330px', height: '155px' }"
    ref="verify" />
</template>

<script setup lang="ts">
import {
  Button, Field, Form, Image, NavBar, showNotify, showToast,
} from 'vant';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

import { getCaptchaCode, register } from '@/api';
import Logo from '@/assets/images/kuaihs.png';

import Verify from '../components/verifition/Verify.vue';
import LoginInstance from '../models/LoginInstance';

const router = useRouter();

const verify = ref({} as any);
const isVerify = ref(false);

const form = ref({
  validate: () => Promise.resolve(),
});
const params = ref<LoginInstance>(new LoginInstance());

// 验证规则
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
];

const passwordRules = [
  { required: true, message: '请填写密码' },
  {
    pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/,
    message: '密码必须包含大小写字母和数字，长度在8-16之间',
  },
];

const handleVerify = () => {
  verify.value.show();
};

// 验证码相关
const countdown = ref(0);
const showSendCode = computed(() => /^1[3-9]\d{9}$/.test(params.value.phoneNumber) && countdown.value === 0);
const smsCodeLoading = ref(false);
// 发送验证码
const sendSmsCode = async () => {
  if (!showSendCode.value) return;
  if (!isVerify.value) {
    handleVerify();
    return;
  }
  try {
    smsCodeLoading.value = true;
    const { data } = await getCaptchaCode(params.value);
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
    showToast(data.msg || '验证码已发送');
  } catch (error) {
    showToast('发送失败');
  } finally {
    smsCodeLoading.value = false;
    isVerify.value = false;
  }
};

// 提交注册
const loading = ref(false);
const handleSubmit = async () => {
  loading.value = true;
  try {
    await form.value.validate();
    const { data } = await register(params.value);
    showNotify({ message: data.msg || '注册成功', type: 'success' });
    router.replace({ name: 'LoginPage' });
  } catch (error) {
    //
  } finally {
    loading.value = false;
  }
};

type TSucess = {
  captchaVerification: string
}

const success = async (param:TSucess) => {
  params.value.captchaVerification = param.captchaVerification;
  isVerify.value = true;
  sendSmsCode();
};

// 跳转登录
const gotoLogin = () => {
  router.replace({ name: 'LoginPage' });
};

const showPassword = ref(false);
const rightIcon = computed(() => (showPassword.value ? 'eye-o' : 'closed-eye'));
const passwordType = computed(() => (showPassword.value ? 'text' : 'password'));
</script>

<style lang="less" scoped>
.register-page {
  height: 100%;
  padding: 40px 20px;

  .register-header {
    text-align: center;
    color: #fff;
    margin-bottom: 40px;

    h2 {
      font-size: 24px;
      margin: 10px 0;
    }

    p {
      font-size: 16px;
      opacity: 0.9;
    }
  }

  .form {
    width: 100%;

    .field {
      background: var(--van-gray-2);
      margin-bottom: 20px;
      border-radius: 50px;
    }
  }

  .actions-button {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-top: 20px;

    .extra-actions {
      display: flex;
      justify-content: flex-end;
      font-size: 14px;
      color: var(--van-primary-color);
      padding: 0 20px;
    }
  }

}
</style>
